package com.tjec.project.businessWorkbench.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.constant.Constants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.security.service.TokenService;

import com.tjec.project.businessWorkbench.domain.BmsBusiness;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessMapper;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMapper;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.system.service.IBmsAttachmentProjectBusinessService;
import com.tjec.project.system.service.IBmsMdBusinessCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tjec.project.businessWorkbench.mapper.BmsProjectDocCatalogMapper;
import com.tjec.project.businessWorkbench.mapper.BmsProjectDocMapper;
import com.tjec.project.businessWorkbench.domain.BmsProjectDoc;
import com.tjec.project.businessWorkbench.domain.BmsProjectDocCatalog;
import com.tjec.project.businessWorkbench.dto.BmsAttachmentDto;
import com.tjec.project.businessWorkbench.dto.WholeDocQueryDto;
import com.tjec.project.businessWorkbench.service.IBmsProjectDocCatalogService;
import com.tjec.project.businessWorkbench.service.IBmsProjectDocService;
import com.tjec.project.businessWorkbench.vo.WholeDocQueryVo;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import org.springframework.util.CollectionUtils;

/**
 * 项目文档 Service业务层处理
 *
 * @author pangyongfeng
 * @date 2020-04-27
 */
@Service
public class BmsProjectDocServiceImpl implements IBmsProjectDocService {
    @Autowired
    private BmsProjectDocMapper bmsProjectDocMapper;
    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Autowired
    private IBmsProjectDocCatalogService bmsProjectDocCatalogService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private BmsProjectMapper bmsProjectMapper;
    @Autowired
    private BmsProjectDocCatalogMapper bmsProjectDocCatalogMapper;
    @Autowired
    private BmsBusinessMapper bmsBusinessMapper;

    @Autowired
    private IBmsProjectMemberService bmsProjectMemberService;

    @Autowired
    private IBmsMdBusinessCategoryService bmsMdBusinessCategoryService;

    @Autowired
    private IBmsAttachmentProjectBusinessService bmsAttachmentProjectBusinessService;

    List<BmsProjectDocCatalog> childNode = new ArrayList<BmsProjectDocCatalog>();
    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;

    /**
     * 查询项目文档
     *
     * @param id 项目文档 ID
     * @return 项目文档
     */
    @Override
    public BmsProjectDoc selectBmsProjectDocByGuid(String guid) {
        BmsProjectDoc result = bmsProjectDocMapper.selectBmsProjectDocByGuid(guid);
        if (result != null && result.getAttachments() != null && result.getAttachments().size() == 1 && result.getAttachments().get(0).getFileId() == null) {
            result.setAttachments(null);
        }else {
        	result.getAttachments().forEach(it -> {
                if (StringUtils.isNotBlank(it.getFileId())) {
                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                }
            });
        }
        return result;
    }

    /**
     * 查询项目文档 列表
     *
     * @param bmsProjectDoc 项目文档
     * @return 项目文档
     */
    @Override
    public void selectBmsProjectDocList(BmsProjectDoc bmsProjectDoc) {
        childNode = new ArrayList<BmsProjectDocCatalog>();
        //判断目录id catalogId是否等于“0”，如果等于“0”，直接查询本业务下所有附件，如果不等于“0”
        //首先递归查询该目录下所有的目录id，根据所有目录id查询到附件
        if(StringUtils.isNotBlank(bmsProjectDoc.getBusinessId())){
            List<String> businessIds = new ArrayList<>();
            businessIds.add(bmsProjectDoc.getBusinessId());
            bmsProjectDoc.setBusinessIds(businessIds);
        }
        if (StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())) {


            BmsProjectDocCatalog docCatalog = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogByGuid(bmsProjectDoc.getCatalogId());
            if ("0".equals(docCatalog.getParentId())) {
                bmsProjectDoc.setType(null);
//                return bmsProjectDocMapper.selectAllProjectDocQueryList(bmsProjectDoc);
            } else {
                List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogService.selectBmsProjectDocCatalogList(new BmsProjectDocCatalog());
                treeMenuList(bmsProjectDocCatalogs, bmsProjectDoc.getCatalogId());
                List<String> guids = new ArrayList<String>();

                for (BmsProjectDocCatalog node : childNode) {
                    guids.add(node.getGuid());
                    System.out.println(" childNode id = " + node.getGuid());
                }
                guids.add(bmsProjectDoc.getCatalogId());
                bmsProjectDoc.setGuids(guids);
                bmsProjectDoc.setCatalogId(null);
                /*List<BmsProjectDoc> list = bmsProjectDocMapper.selectAllProjectDocQueryList(bmsProjectDoc);
                list.forEach(item -> {
                    List<BmsAttachmentDto> attachments = item.getAttachments();
                    attachments.forEach(it -> {
                        if (StringUtils.isNotBlank(it.getFileId())) {
                            it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                        }
                    });

                });
                return list;*/
            }
        } else {
            /*List<BmsProjectDoc> list = bmsProjectDocMapper.selectAllProjectDocQueryList(bmsProjectDoc);
            list.forEach(item -> {
                List<BmsAttachmentDto> attachments = item.getAttachments();
                attachments.forEach(it -> {
                    if (StringUtils.isNotBlank(it.getFileId())) {
                        it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                    }
                });

            });
            return list;*/
        }

    }
    
    /**
     * 查询项目文档列表-成果校审
     *
     * @param bmsProjectDoc 项目文档
     * @return 项目文档
     */
    @Override
    public List<BmsProjectDoc> selectBmsProjectDocListByResult(BmsProjectDoc bmsProjectDoc) {
        childNode = new ArrayList<BmsProjectDocCatalog>();
        //判断目录id catalogId是否等于“0”，如果等于“0”，直接查询本业务下所有附件，如果不等于“0”
        //首先递归查询该目录下所有的目录id，根据所有目录id查询到附件
        if (StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())) {


            BmsProjectDocCatalog docCatalog = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogByGuid(bmsProjectDoc.getCatalogId());
            if ("0".equals(docCatalog.getParentId())) {
                return bmsProjectDocMapper.selectBmsProjectDocList(bmsProjectDoc);
            } else {
                List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogService.selectBmsProjectDocCatalogList(new BmsProjectDocCatalog());
                treeMenuList(bmsProjectDocCatalogs, bmsProjectDoc.getCatalogId());
                List<String> guids = new ArrayList<String>();

                for (BmsProjectDocCatalog node : childNode) {
                    guids.add(node.getGuid());
                    System.out.println(" childNode id = " + node.getGuid());
                }
                guids.add(bmsProjectDoc.getCatalogId());
                bmsProjectDoc.setGuids(guids);
                bmsProjectDoc.setCatalogId(null);
                
                List<BmsProjectDoc> list = new ArrayList<BmsProjectDoc>();
                BmsProjectDoc bmsProjectDocEntity =new BmsProjectDoc();
                bmsProjectDocEntity.setType("3");
                List<BmsAttachmentDto> attachmentsList = bmsAttachmentMapper.selectBmsAttachmentByBizIds(guids);
                bmsProjectDocEntity.setAttachments(attachmentsList);
                list.add(bmsProjectDocEntity);
                
                list.forEach(item -> {
                    List<BmsAttachmentDto> attachments = item.getAttachments();
                    attachments.forEach(it -> {
                        if (StringUtils.isNotBlank(it.getFileId())) {
                            it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                        }
                    });

                });
                return list;
            }
        } else {
            List<BmsProjectDoc> list = bmsProjectDocMapper.selectBmsProjectDocList(bmsProjectDoc);
            list.forEach(item -> {
                List<BmsAttachmentDto> attachments = item.getAttachments();
                attachments.forEach(it -> {
                    if (StringUtils.isNotBlank(it.getFileId())) {
                        it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                    }
                });

            });
            return list;
        }

    }

    public List<BmsProjectDocCatalog> treeMenuList(List<BmsProjectDocCatalog> treeNodes, String pid) {

        List<BmsProjectDocCatalog> tempTreeNode = new ArrayList<BmsProjectDocCatalog>();
        List<BmsProjectDocCatalog> tempTreeNode1 = new ArrayList<BmsProjectDocCatalog>();
        for (BmsProjectDocCatalog node : treeNodes) {
            if (pid.equals(node.getParentId())) {
                //说明存在子节点

                tempTreeNode1 = treeMenuList(treeNodes, node.getGuid());

                childNode.add(node);
                //用于让上一级判断是否存在子节点
                //因为存在子节点则tempTreeNode不为空
                //函数结束后返回tempTreeNode给上一级以供判断
                tempTreeNode.add(node);
                System.out.println("当前节点存在子节点");
            }

        }
        return tempTreeNode;
    }

    /**
     * 新增项目文档
     *
     * @param bmsProjectDoc 项目文档
     * @return 结果
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int insertBmsProjectDoc(BmsProjectDoc bmsProjectDoc) {
    	
        int res = bmsProjectDocMapper.insertBmsProjectDoc(bmsProjectDoc);
		bmsProjectDocCatalogMapper.updateBmsProjectDocCatalogCountsPlus(bmsProjectDoc.getCatalogId());
		
        if (bmsProjectDoc.getAttachmentIds() != null && bmsProjectDoc.getAttachmentIds().size() > 0) {
            int updateRes = bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(bmsProjectDoc.getAttachmentIds(), bmsProjectDoc.getGuid(), AttachmentConstants.PROJECT_DOC, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
            bmsAttachmentProjectBusinessService.insertBmsAttachmentProjectBusinessByBusinessId(bmsProjectDoc.getAttachmentIds(), bmsProjectDoc.getBusinessId());
            return updateRes;
        } else {
            return res;
        }
    }

    /**
     * 修改项目文档
     *
     * @param bmsProjectDoc 项目文档
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateBmsProjectDoc(BmsProjectDoc bmsProjectDoc) {
        bmsProjectDoc.setUpdateTime(DateUtils.getNowDate());
        int result = bmsProjectDocMapper.updateBmsProjectDoc(bmsProjectDoc);

        String[] guIds = {bmsProjectDoc.getGuid()};
        bmsAttachmentMapper.updateBmsAttachmentByGuids(guIds, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());

        if (bmsProjectDoc.getAttachmentIds() != null && bmsProjectDoc.getAttachmentIds().size() > 0) {
            int updateRes = bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(
                    bmsProjectDoc.getAttachmentIds(), bmsProjectDoc.getGuid(),
                    AttachmentConstants.PROJECT_DOC, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
            bmsAttachmentProjectBusinessService.insertBmsAttachmentProjectBusinessByBusinessId(bmsProjectDoc.getAttachmentIds(), bmsProjectDoc.getBusinessId());
            BmsProjectDoc projectDoc = new BmsProjectDoc();
            projectDoc.setGuid(bmsProjectDoc.getGuid());
            projectDoc.setCreateTime(DateUtils.getNowDate());
            projectDoc.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
            bmsProjectDocMapper.updateBmsProjectDoc(projectDoc);
            return updateRes;
        } else {
            BmsProjectDoc projectDoc = new BmsProjectDoc();
            projectDoc.setGuid(bmsProjectDoc.getGuid());
            projectDoc.setCreateTime(null);
            projectDoc.setCreateBy(null);
            bmsProjectDocMapper.updateBmsProjectDoc(projectDoc);
            return result;
        }
    }

    /**
     * 批量删除项目文档
     *
     * @param guids 需要删除的项目文档 ID
     * @return 结果
     * @throws Exception
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int deleteBmsProjectDocByGuids(String[] guids) throws Exception {
    	//删除目录下的文件数量
    	if(guids!=null && guids.length>0) {
    		for (String guid : guids) {
    			bmsProjectDocCatalogMapper.updateBmsProjectDocCatalogCountsSub(guid);
			}
    	}
    	
        //首先，逻辑删除该文件标题下的所有附件
        int res = bmsAttachmentMapper.updateBmsAttachmentByGuids(guids, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        if (res < 0) throw new Exception("逻辑删除文件标题下的附件失败，guids=" + guids);
        return bmsProjectDocMapper.deleteBmsProjectDocByGuids(guids);
    }

    /**
     * 删除项目文档 信息
     *
     * @param guid 项目文档 ID
     * @return 结果
     */
    @Override
    public int deleteBmsProjectDocByGuid(String guid) {
        return bmsProjectDocMapper.deleteBmsProjectDocByGuid(guid);
    }

    @Override
    public int moveBmsProjectDoc(String catalogId, String updateBy, ArrayList<String> guid) {
        return bmsProjectDocMapper.moveBmsProjectDoc(catalogId, updateBy, guid);
    }

    /**
     * 项目主页-文档查询
     *
     * @param bmsProjectDoc 项目文档
     * @return
     */
    @Override
    public List<BmsProjectDoc> selectBmsProjectDocQueryList(BmsProjectDoc bmsProjectDoc) {
        return bmsProjectDocMapper.selectBmsProjectDocQueryList(bmsProjectDoc);

    }

    /**
     * 解析文档查询参数
     * @param bmsProjectDoc
     */
    @Override
    public BmsProjectDoc parsingParamBmsProjectDoc(BmsProjectDoc bmsProjectDoc){
        childNode = new ArrayList<>();
        List<String> businesssIds =  new ArrayList<>();
        if(StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())) {
            //是否为项目Id，默认传参或树结构根节点
            BmsProject bmsProject = bmsProjectMapper.selectBmsProjectByGuid(bmsProjectDoc.getCatalogId());
            if (bmsProject != null) {
                List<BmsBusiness> bmsBusinesss = bmsBusinessMapper.selectBmsBusinessByProjectId(bmsProject.getGuid());
                Set<String> engineeringBiddingList = bmsMdBusinessCategoryService.selectEngineeringBidding();
                //过滤当前登录人不是招标组长、组员并且为项目成员，业务中存在招标代理类业务
                bmsBusinesss = bmsBusinesss.stream().filter(b->!(bmsProjectMemberService.isTenderMembers(SecurityUtils.getLoginUser().getUser().getUserId(), b)&&engineeringBiddingList.contains(b.getBusinessCategoryId()))).collect(Collectors.toList());
                for (BmsBusiness businesss : bmsBusinesss) {
                    businesssIds.add(businesss.getGuid());
                }
                bmsProjectDoc.setBusinessIds(businesssIds);
                bmsProjectDoc.setCatalogId(null);
            }else{
                //判断是否为第二层树节点
                BmsProjectDocCatalog docCatalog = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogByGuid(bmsProjectDoc.getCatalogId());
                businesssIds.add(docCatalog.getBusinessId());
                bmsProjectDoc.setBusinessIds(businesssIds);
                //不为0，即第二层以下树节点
                if (!"0".equals(docCatalog.getParentId())) {
                    BmsProjectDocCatalog bmsProjectDocCatalogParam = new BmsProjectDocCatalog();
                    bmsProjectDocCatalogParam.setBusinessId(docCatalog.getBusinessId());
                    List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogService.selectBmsProjectDocCatalogList(bmsProjectDocCatalogParam);
                    treeMenuList(bmsProjectDocCatalogs, bmsProjectDoc.getCatalogId());
                    List<String> guids = new ArrayList<String>();

                    for (BmsProjectDocCatalog node : childNode) {
                        guids.add(node.getGuid());
                    }
                    guids.add(bmsProjectDoc.getCatalogId());
                    bmsProjectDoc.setGuids(guids);
                    bmsProjectDoc.setCatalogId(null);
                }
            }
        }
        return bmsProjectDoc;
    }

    @Override
    public List<BmsProjectDoc> getDocByCatalogId(String catalogId) {
        return bmsProjectDocMapper.getDocByCatalogId(catalogId);
    }

    @Override
    public List<BmsProjectDoc> selectAllProjectDocQueryList(BmsProjectDoc bmsProjectDoc) {
        List<BmsProjectDoc> list = bmsProjectDocMapper.selectAllProjectDocQueryList(bmsProjectDoc);
        list.forEach(item -> {
            List<BmsAttachmentDto> attachments = item.getAttachments();
            attachments.forEach(it -> {
                if (StringUtils.isNotBlank(it.getFileId())) {
                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                }
            });
        });
        return list;
    }

	@Override
	public List<WholeDocQueryDto> wholeDocQuery(WholeDocQueryVo wholeDocQueryVo) {
		List<WholeDocQueryDto> list = bmsProjectDocMapper.wholeDocQuery(wholeDocQueryVo);
		list.forEach(item -> {
            List<BmsAttachmentDto> attachments = item.getAttachments();
            attachments.forEach(it -> {
                if (StringUtils.isNotBlank(it.getFileId())) {
                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                }
            });
        });
		
		return list;
	}

    /*@Override
    public Integer countSelectAllProjectDocQueryList(BmsProjectDoc bmsProjectDoc) {
        if(CollectionUtils.isEmpty(bmsProjectDoc.getBusinessIds())&&CollectionUtils.isEmpty(bmsProjectDoc.getGuids())){
            return 0;
        }else{
            return bmsProjectDocMapper.countSelectAllProjectDocQueryList(bmsProjectDoc);
        }
    }*/

    @Override
    public Integer countProjectDocCatalog(BmsProjectDoc bmsProjectDoc) {
        return bmsProjectDocMapper.countProjectDocCatalog(bmsProjectDoc);
    }

    /**
     * 获取项目文档子目录
     * @param bmsProjectDoc
     * @return
     */
    @Override
    public List<BmsProjectDocCatalog> getProjectDocCatalogChildren(BmsProjectDoc bmsProjectDoc) {
        List<BmsProjectDocCatalog> list = new ArrayList<>();
        if(StringUtils.isBlank(bmsProjectDoc.getBusinessId())||StringUtils.isBlank(bmsProjectDoc.getCatalogId())){
            return list;
        }
        BmsProjectDocCatalog bmsProjectDocCatalogParam = new BmsProjectDocCatalog();
        bmsProjectDocCatalogParam.setBusinessId(bmsProjectDoc.getBusinessId());
        List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogService.selectBmsProjectDocCatalogList(bmsProjectDocCatalogParam);
        childNode = new ArrayList<>();
        treeMenuList(bmsProjectDocCatalogs, bmsProjectDoc.getCatalogId());
        list = childNode;
        return list;
    }
}
